// pages/daily-work-report/daily-work-report.js
const app = getApp()

Page({
  data: {
    orders: [],
    workItems: [], // 工作项目列表
    workDate: '',
    remark: '',
    loading: true,
    submitting: false,
    
    // 统计数据
    totalWorkItems: 0,
    totalQuantity: 0,
    totalWorkHours: 0,
    estimatedWage: 0
  },

  onLoad() {
    this.loadOrders()
    this.setWorkDate()
  },

  onShow() {
    // 如果已有订单数据，重新加载
    if (this.data.orders.length === 0) {
      this.loadOrders()
    }
  },

  onPullDownRefresh() {
    this.setData({
      refreshing: true
    })
    this.loadOrders().then(() => {
      wx.stopPullDownRefresh()
      this.setData({
        refreshing: false
      })
    })
  },

  // 设置工作日期为今天
  setWorkDate() {
    const today = new Date()
    const year = today.getFullYear()
    const month = String(today.getMonth() + 1).padStart(2, '0')
    const day = String(today.getDate()).padStart(2, '0')
    this.setData({
      workDate: `${year}-${month}-${day}`
    })
  },

  // 加载订单列表
  loadOrders() {
    console.log('开始加载订单列表')
    this.setData({ loading: true })
    
    return app.userRequest({
      url: '/getOrders'
    }).then((res) => {
      console.log('获取订单列表成功:', res)
      this.setData({
        orders: res.data || [],
        loading: false
      })
    }).catch((err) => {
      console.error('获取订单列表失败:', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '获取订单失败',
        icon: 'none'
      })
    })
  },

  // 工作日期变化
  onWorkDateChange(e) {
    this.setData({
      workDate: e.detail.value
    })
  },

  // 添加工作项目
  addWorkItem() {
    const workItems = this.data.workItems
    workItems.push({
      selectedOrder: null,
      selectedModel: null,
      orderModels: [],
      quantity: '',
      workHours: '',
      workDescription: '',
      images: []
    })
    
    this.setData({
      workItems: workItems
    })
    
    this.updateStats()
  },

  // 删除工作项目
  deleteWorkItem(e) {
    const index = e.currentTarget.dataset.index
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这个工作项目吗？',
      success: (res) => {
        if (res.confirm) {
          const workItems = this.data.workItems
          workItems.splice(index, 1)
          
          this.setData({
            workItems: workItems
          })
          
          this.updateStats()
        }
      }
    })
  },

  // 订单选择
  onOrderChange(e) {
    const index = e.currentTarget.dataset.index
    const orderIndex = e.detail.value
    const order = this.data.orders[orderIndex]
    
    const workItems = this.data.workItems
    workItems[index].selectedOrder = order
    workItems[index].selectedModel = null
    workItems[index].orderModels = []
    workItems[index].quantity = ''
    workItems[index].workHours = ''
    workItems[index].workDescription = ''
    workItems[index].images = []
    
    this.setData({
      workItems: workItems
    })
    
    if (order && order.id) {
      this.loadOrderModels(order.id, index)
    }
    
    this.updateStats()
  },

  // 加载订单型号
  loadOrderModels(orderId, itemIndex) {
    console.log('开始加载订单型号，订单ID:', orderId, '项目索引:', itemIndex)
    
    const requestUrl = '/getOrderModels?order_id=' + orderId
    console.log('请求URL:', requestUrl)
    
    app.userRequest({
      url: requestUrl,
      method: 'GET'
    }).then((res) => {
      console.log('获取订单型号成功:', res)
      
      if (Array.isArray(res.data)) {
        // 计算每个型号的可报工数量
        const orderModelsWithAvailableQuantity = res.data.map(model => {
          const totalQuantity = model.order_quantity || 0
          const allocatedQuantity = model.allocated_quantity || 0
          const activeReportQuantity = model.active_report_quantity || 0
          const availableQuantity = Math.max(0, totalQuantity - allocatedQuantity - activeReportQuantity)
          
          return {
            ...model,
            available_quantity: availableQuantity,
            allocated_quantity: allocatedQuantity,
            active_report_quantity: activeReportQuantity,
            order_quantity: totalQuantity
          }
        })
        
        const workItems = this.data.workItems
        workItems[itemIndex].orderModels = orderModelsWithAvailableQuantity
        
        this.setData({
          workItems: workItems
        })
      }
    }).catch((err) => {
      console.error('获取订单型号失败:', err)
      wx.showToast({
        title: err.msg || '获取型号失败',
        icon: 'none'
      })
    })
  },

  // 型号选择
  onModelChange(e) {
    const index = e.currentTarget.dataset.index
    const modelIndex = e.detail.value
    const model = this.data.workItems[index].orderModels[modelIndex]
    
    const workItems = this.data.workItems
    workItems[index].selectedModel = model
    workItems[index].quantity = ''
    workItems[index].workHours = ''
    workItems[index].workDescription = ''
    workItems[index].images = []
    
    this.setData({
      workItems: workItems
    })
    
    this.updateStats()
  },

  // 数量输入
  onQuantityInput(e) {
    const index = e.currentTarget.dataset.index
    const quantity = parseInt(e.detail.value) || 0
    
    const workItems = this.data.workItems
    workItems[index].quantity = quantity.toString()
    
    this.setData({
      workItems: workItems
    })
    
    this.updateStats()
  },

  // 工时输入
  onWorkHoursInput(e) {
    const index = e.currentTarget.dataset.index
    const workHours = parseFloat(e.detail.value) || 0
    
    const workItems = this.data.workItems
    workItems[index].workHours = workHours.toString()
    
    this.setData({
      workItems: workItems
    })
    
    this.updateStats()
  },

  // 工作内容描述输入
  onWorkDescriptionInput(e) {
    const index = e.currentTarget.dataset.index
    const workDescription = e.detail.value
    
    const workItems = this.data.workItems
    workItems[index].workDescription = workDescription
    
    this.setData({
      workItems: workItems
    })
  },

  // 备注输入
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  // 选择图片
  chooseImage(e) {
    const itemIndex = e.currentTarget.dataset.itemIndex
    const workItems = this.data.workItems
    const currentImages = workItems[itemIndex].images
    const remainingCount = 9 - currentImages.length
    
    if (remainingCount <= 0) {
      wx.showToast({
        title: '已达到最大图片数量',
        icon: 'none'
      })
      return
    }
    
    wx.chooseImage({
      count: remainingCount,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        if (res.tempFilePaths && res.tempFilePaths.length > 0) {
          this.uploadImages(res.tempFilePaths, itemIndex)
        }
      },
      fail: (err) => {
        console.error('选择图片失败:', err)
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    })
  },

  // 上传图片
  uploadImages(tempFilePaths, itemIndex) {
    console.log('开始上传图片，文件路径:', tempFilePaths, '项目索引:', itemIndex)
    
    if (!tempFilePaths || tempFilePaths.length === 0) {
      wx.showToast({
        title: '没有选择文件',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({
      title: '上传中...'
    })

    const uploadPromises = tempFilePaths.map((filePath, index) => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: app.globalData.userApiUrl + '/uploadImage',
          filePath: filePath,
          name: 'file',
          header: {
            'Authorization': 'Bearer ' + wx.getStorageSync('token')
          },
          success: (res) => {
            try {
              const data = JSON.parse(res.data)
              if (data.code === 1) {
                resolve(data.data.url)
              } else {
                reject(new Error(data.msg))
              }
            } catch (e) {
              reject(new Error('响应解析失败'))
            }
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    })

    Promise.all(uploadPromises).then(imageUrls => {
      console.log('所有图片上传成功:', imageUrls)
      
      // 更新工作项目的图片列表
      const workItems = this.data.workItems
      workItems[itemIndex].images = [...workItems[itemIndex].images, ...imageUrls]
      
      this.setData({
        workItems: workItems
      })
      
      wx.hideLoading()
      wx.showToast({
        title: '上传成功',
        icon: 'success'
      })
    }).catch(err => {
      console.error('图片上传失败:', err)
      wx.hideLoading()
      wx.showToast({
        title: '上传失败: ' + (err.message || err.errMsg || '未知错误'),
        icon: 'none',
        duration: 3000
      })
    })
  },

  // 删除图片
  deleteImage(e) {
    const itemIndex = e.currentTarget.dataset.itemIndex
    const imageIndex = e.currentTarget.dataset.imageIndex
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这张图片吗？',
      success: (res) => {
        if (res.confirm) {
          const workItems = this.data.workItems
          workItems[itemIndex].images.splice(imageIndex, 1)
          
          this.setData({
            workItems: workItems
          })
        }
      }
    })
  },

  // 预览图片
  previewImage(e) {
    const url = e.currentTarget.dataset.url
    wx.previewImage({
      urls: [url],
      current: url
    })
  },

  // 更新统计数据
  updateStats() {
    const workItems = this.data.workItems
    let totalWorkItems = workItems.length
    let totalQuantity = 0
    let totalWorkHours = 0
    let estimatedWage = 0
    
    workItems.forEach(item => {
      if (item.quantity) {
        totalQuantity += parseInt(item.quantity) || 0
      }
      if (item.workHours) {
        totalWorkHours += parseFloat(item.workHours) || 0
      }
      
      // 计算预估工资（计件 + 计时）
      if (item.selectedModel) {
        const quantity = parseInt(item.quantity) || 0
        const workHours = parseFloat(item.workHours) || 0
        const piecePrice = parseFloat(item.selectedModel.piece_price) || 0
        const timePrice = parseFloat(item.selectedModel.time_price) || 0
        
        estimatedWage += (quantity * piecePrice) + (workHours * timePrice)
      }
    })
    
    this.setData({
      totalWorkItems: totalWorkItems,
      totalQuantity: totalQuantity,
      totalWorkHours: totalWorkHours.toFixed(1),
      estimatedWage: estimatedWage.toFixed(2)
    })
  },

  // 提交每日工作报工
  submitDailyReport() {
    const { workItems, workDate, remark } = this.data
    
    if (!workDate) {
      wx.showToast({
        title: '请选择工作日期',
        icon: 'none'
      })
      return
    }
    
    if (workItems.length === 0) {
      wx.showToast({
        title: '请至少添加一个工作项目',
        icon: 'none'
      })
      return
    }
    
    // 验证每个工作项目
    for (let i = 0; i < workItems.length; i++) {
      const item = workItems[i]
      
      if (!item.selectedOrder) {
        wx.showToast({
          title: `工作项目${i + 1}请选择订单`,
          icon: 'none'
        })
        return
      }
      
      if (!item.selectedModel) {
        wx.showToast({
          title: `工作项目${i + 1}请选择产品型号和工序`,
          icon: 'none'
        })
        return
      }
      
      if (!item.quantity || item.quantity <= 0) {
        wx.showToast({
          title: `工作项目${i + 1}请输入工作数量`,
          icon: 'none'
        })
        return
      }
      
      if (!item.workHours || item.workHours <= 0) {
        wx.showToast({
          title: `工作项目${i + 1}请输入工作时长`,
          icon: 'none'
        })
        return
      }
      
      if (!item.workDescription || item.workDescription.trim() === '') {
        wx.showToast({
          title: `工作项目${i + 1}请填写工作内容描述`,
          icon: 'none'
        })
        return
      }
    }
    
    // 构建提交数据
    const reportData = {
      work_date: workDate,
      remark: remark,
      work_items: workItems.map(item => ({
        order_id: item.selectedOrder.id,
        model_id: item.selectedModel.model_id,
        process_id: item.selectedModel.process_id,
        quantity: parseInt(item.quantity),
        work_hours: parseFloat(item.workHours),
        work_description: item.workDescription,
        images: item.images
      }))
    }
    
    this.setData({
      submitting: true
    })
    
    app.userRequest({
      url: '/submitDailyWorkReport',
      method: 'POST',
      data: reportData
    }).then((res) => {
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      })
      
      // 重置表单
      this.setData({
        workItems: [],
        remark: '',
        submitting: false,
        totalWorkItems: 0,
        totalQuantity: 0,
        totalWorkHours: 0,
        estimatedWage: 0
      })
      
      // 延迟返回上一页
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
    }).catch((err) => {
      this.setData({
        submitting: false
      })
      wx.showToast({
        title: err.msg || '提交失败',
        icon: 'none'
      })
    })
  }
})
